<template>
  <div class="one">
    <div><p><label about='inStr'>请将mybatis的sql日志粘贴到这里:</label></p>
      <p><textarea v-model='inValue' name='inStr' rows='25' cols='150'></textarea></p>
      <p>
        <button @click="commitFn" style="width:80px;height:40px">解析</button>
        <button @click="clear" style="width:80px;height:40px">清除</button>
      </p>
    </div>

    <div>
      <div v-for='(item,index) in outValue' :key="index"
           style='border-bottom:2px solid black;padding: 5px; padding-top: 2px'>
        <span class="copy-btn" v-clipboard:copy="item" v-clipboard:success="onCopy"
              v-clipboard:error="onError">复制</span>
        <pre>{{item}}</pre>
      </div>

    </div>

  </div>
</template>

<script>

import sqlFormatter from 'sql-formatter'

const STR_PREPARING = '==>  Preparing:'
const STR_PARAMETERS = '==> Parameters:'
export default {
  name: 'Home',
  components: {},
  data: function () {
    return {
      inValue: '',
      outValue: []
    }
  },
  methods: {
    commitFn: function () {
      this.outValue = this.parse(this.inValue)
    },
    clear () {
      this.inValue = ''
      this.outValue = []
    },
    // 复制成功时的回调函数
    onCopy (e) {
      this.$my_message('内容已复制到剪切板！', 'success')
    },
    // 复制失败时的回调函数
    onError (e) {
      this.$my_message('抱歉，复制失败！', 'error')
    },
    copyText (obj) {
    },
    parse (inValue) {
      let split = inValue.split('\n')
      let sb = ''
      let list = []
      if (split && split.length > 0) {
        for (let i = 0; i < split.length; i++) {
          let line = split[i]
          if (!line || line.trim().length === 0) continue
          if (line.indexOf(STR_PREPARING) > 0) {
            let subLine = line.substring(line.indexOf(STR_PREPARING) + 15)
            sb = subLine
            console.log('1:', sb)
            // 为这一行选择配对的行
            let rightLine = this.selectRightLine(line, split, i)
            if (rightLine.indexOf(STR_PARAMETERS) > 0) {
              let rightStr = rightLine.substring(rightLine.indexOf(STR_PARAMETERS) + 15)
              if (sb.length === 0) continue
              console.log('2', rightStr)
              let params = rightStr.split(',')
              console.log(params)
              for (let p of params) {
                p = p.trim()
                if (!p || p === '') continue
                let value = p.substring(0, p.indexOf('('))
                value = value || (p.includes('null') ? 'NULL' : '')
                let type = p.substring(p.indexOf('(') + 1, p.indexOf(')'))
                console.log(value, type)
                if ((type.toLowerCase()) === 'string' || (type.toLowerCase()) === 'timestamp') {
                  sb = sb.replace(/\?/, '\'' + value + '\'')
                } else {
                  sb = sb.replace(/\?/, value)
                }
              }
              let res = sqlFormatter.format(sb.toString())
              list.push(res)
            }
            sb = ''
          }
        }
      }
      return list
    },
    selectRightLine (line, split, start) {
      let map = new Map()
      let frontArr = line.substring(0, line.indexOf(STR_PREPARING)).split('')
      for (let i = start; i < split.length; i++) {
        let rightLine = split[i]
        if (rightLine.includes(STR_PARAMETERS)) {
          let rigthArr = rightLine.substring(0, rightLine.indexOf(STR_PARAMETERS)).split('')
          if (rigthArr.length !== frontArr.length) continue
          let count = 0
          for (let j = 0; j < frontArr.length; j++) {
            if (frontArr[j] === rigthArr[j]) count++
          }
          // console.log(start, "...", rightLine)
          map.set(i, count)
        } else {
          continue
        }
      }
      console.log(map)
      let lineNo = this.getMaxLineNo(map)
      console.log(start, '...', lineNo)
      return split[lineNo]
    },
    getMaxLineNo (map) {
      // eslint-disable-next-line one-var
      let max = 0, lineNo = 0
      for (let [key, value] of map.entries()) {
        if (value > max) {
          max = value
          lineNo = key
        } else if (value === max && lineNo > key) {
          lineNo = key // 选行号小的
        }
      }
      return lineNo
    }
  }
}
</script>

<style scoped>
  .copy-btn {
    display: inline-block;
    border: 1px solid #42b983;
    color: blue;
    cursor: pointer;
  }
</style>
